package com.hele.sts.pub;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileManager
{
	private static final Logger logger = LoggerFactory.getLogger(FileManager.class);
  public String delAll(File f, String notDelete)
  {
    if (!f.exists()) {
      return "指定目录不存在:" + f.getName();
    }
    boolean rslt = true;
    if (!(rslt = f.delete()))
    {
      File[] subs = f.listFiles();
      for (int i = 0; i <= subs.length - 1; i++)
      {
        if ((subs[i].isDirectory()) && (!subs[i].getPath().equals(notDelete))) {
          delAll(subs[i], "");
        }
        rslt = subs[i].delete();
      }
      rslt = f.delete();
    }
    if (!rslt) {
      return "无法删除:" + f.getName();
    }
    return "";
  }
  
  public static String downLoadFile(String IpAddress, String FtpUser, String Ftppassword, String FileName)
  {
    FTPClient ftp = new FTPClient();
    ftp.enterLocalPassiveMode();
    try
    {
      ftp.connect(IpAddress);
    }
    catch (SocketException e1)
    {
      e1.printStackTrace();
    }
    catch (IOException e1)
    {
      e1.printStackTrace();
    }
    try
    {
      ftp.login(FtpUser, Ftppassword);
    }
    catch (IOException e1)
    {
      e1.printStackTrace();
    }
    try
    {
      ftp.logout();
    }
    catch (IOException e1)
    {
      e1.printStackTrace();
    }
    IOException e = null;
    e.printStackTrace();
    if (!ftp.isConnected()) {
      try
      {
        ftp.disconnect();
      }
      catch (IOException e1)
      {
        e1.printStackTrace();
      }
    }
    IOException ioe = null;
    ioe.printStackTrace();
    return "";
  }
  
  public int fileCopy(String sourceFile, String destinctFile)
    throws IOException
  {
    String fileName = sourceFile;
    int pos = fileName.lastIndexOf("//");
    if (pos > 0) {
      fileName = fileName.substring(pos + 1, fileName.length());
    }
    String lastPath = destinctFile;
    File objFile = new File(lastPath);
    System.out.println("lastPath" + lastPath);
    if ((objFile.exists()) && (!objFile.delete())) {
      return -1;
    }
    objFile.createNewFile();
    FileInputStream fis = new FileInputStream(sourceFile);
    FileOutputStream fos = new FileOutputStream(objFile);
    System.out.println("sourceFile" + sourceFile);
    byte[] buf = new byte[1024];
    for (int i = 0; (i = fis.read(buf)) != -1;) {
      fos.write(buf, 0, i);
    }
    fis.close();
    fos.close();
    return -2;
  }
  
  public static boolean getDataFiles(String server, String username, String password, String sourceFile, String destinationFile)
    throws SocketException, IOException
  {
	  logger.debug("start...");
    sourceFile = sourceFile.replace('\\', '/');
    destinationFile = destinationFile.replace('\\', '/');
    String fileName = sourceFile;
    String folder = "";
    int pos = fileName.lastIndexOf("/");
    if (pos > 0) {
      fileName = fileName.substring(pos + 1, fileName.length());
    }
    folder = sourceFile.substring(0, pos);
    FTPClient ftp = new FTPClient();
    ftp.connect(server, 21);
    logger.debug("connect ftp...");
    ftp.login(username, password);
    logger.debug("login...");
    ftp.setControlEncoding("GBK");
    ftp.enterLocalPassiveMode();
    ftp.setFileType(2);
    ftp.changeWorkingDirectory(new String(folder.getBytes("gb2312"), "iso-8859-1"));
    logger.debug("chnage dir...");
    int pos1 = destinationFile.lastIndexOf("/");
    if (pos1 > 0)
    {
      String fdr = destinationFile.substring(0, pos1);
      new File(fdr).mkdirs();
    }
    File file = new File(destinationFile);
    FileOutputStream fos = new FileOutputStream(file);
    
    BufferedOutputStream buffOut = null;
	buffOut = new BufferedOutputStream(fos);
		//ftpClient.setControlEncoding("GBK");
    
    
    
    boolean ret = ftp.retrieveFile(fileName, buffOut);
    logger.debug("downloaded...");
    if (buffOut != null)
		buffOut.close();
    if (fos != null) {
      fos.close();
    }
    
    ftp.logout();
    ftp.disconnect();
    return ret;
  }
  
  public static String replaceStr(String str, String destStr, String srcStr)
  {
    StringBuffer retVal = new StringBuffer();
    int findStation = str.indexOf(destStr);
    int resumStation = 0;
    for (; findStation > -1; findStation = str.indexOf(destStr, resumStation))
    {
      retVal.append(str.substring(resumStation, findStation));
      retVal.append(srcStr);
      resumStation = findStation + destStr.length();
    }
    return retVal.toString();
  }
}
